import 'dart:convert';
import 'dart:core';

import 'package:ecy_app_flutter/ecycommon/EcyCommonWidgets.dart';
import 'package:ecy_app_flutter/routes/goods/widgets/EcyGoodsFirstPage.dart';
import 'package:ecy_app_flutter/routes/goods/widgets/EcyGoodsLabelListView.dart';
import 'package:ecy_app_flutter/routes/goods/widgets/EcyNewGoodsView.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import '../../EcyRouter.dart';

import '../../constant/EcyEventConsnt.dart';
import '../../ecycommon/EcyEventBus.dart';
import '../../ecycommon/EcyRequestBaseManager.dart';
import '../../model/EcyApiCommonResponse.dart';
import '../blind_box/blind_box_page.dart';
import 'model/EcyGoodsLabelModel.dart';

class EcyGoodsPage extends EcyCommonBaseWidget {
  late _EcyGoodsPage state;

  EcyGoodsPage();

  @override
  _EcyGoodsPage createState() => _EcyGoodsPage(this);

  reloadData() {
    state.requestData();
  }
}

class _EcyGoodsPage extends EcyCommonBaseWidgetState with SingleTickerProviderStateMixin {
  int _selectIndex = 0;
  late EcyGoodsLabelListView labelListView;
  late EcyGoodsFirstPage goodsFirstPage;
  late BlindBoxPage blindBoxPage;
  late EcyNewGoodsView newGoodsView;
  EcyGoodsLabelModel selectLabelModel = EcyGoodsLabelModel("", "", "", "", "");
  late EcyCommonBaseWidget controller;
  int cartNum = 0;

  PageController _pageController = PageController();

  _EcyGoodsPage(EcyCommonBaseWidget vc) {
    controller = vc;
  }

  _initNotis() {
    EcyEventBus().on(EcyEventConst.kLogined, (arg) {
      if (mounted) {
        _initCartNum();
      }
    });
    EcyEventBus().on(EcyEventConst.kCartChanged, (arg) {
      if (mounted) {
        _initCartNum();
      }
    });
    EcyEventBus().on(EcyEventConst.kLogout, (arg) {
      if (mounted) {
        setState(() {
          cartNum = 0;
        });
      }
    });
  }

  void _initCartNum() async {
    if (mounted) {
      try {
        Map<String, dynamic> response = await EcyRequestbasemanager().get("/app/api/app/cart/count", {});
        var commonResponse = EcyApiCommonResponse.fromJson(response, (response) => json);
        if (commonResponse.code == 0 || commonResponse.code == 200) {
          setState(() {
            cartNum = response["data"] ?? 0;
          });
        } else {
          setState(() {
            cartNum = 0;
          });
        }
      } catch (e) {
        setState(() {
          cartNum = 0;
        });
      }
    }
  }

  @override
  void initState() {
    super.initState();

    _initNotis();

    labelListView = EcyGoodsLabelListView(_selectIndex, (newValue) {
      if (newValue != null) {
        setState(() {
          _selectIndex = newValue;
          _goToPage(_selectIndex);
        });
      }
    });

    goodsFirstPage = EcyGoodsFirstPage(
      key: const Key("goodsFirstPage"),
    );
    blindBoxPage = BlindBoxPage(key: const Key("blindBoxPage"));
    newGoodsView = EcyNewGoodsView(key: const Key("newGoodsView"));
  }

  @override
  void requestData() async {
    super.requestData();
  }

  void _goToPage(int page) {
    _pageController.animateToPage(page, duration: const Duration(milliseconds: 300), curve: Curves.ease);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        backgroundColor: Colors.white,
        appBar: AppBar(
          backgroundColor: Colors.white,
          scrolledUnderElevation: 0,
          titleSpacing: 0,
          title: GestureDetector(
            onTap: () {
              FocusScope.of(context).requestFocus(FocusNode());
              EcyRouter.push(context, EcyRouter.goodsSearchPage, null);
            },
            child: Container(
              width: MediaQuery.of(context).size.width - 50.w,
              margin: const EdgeInsets.only(left: 10, right: 10),
              decoration: BoxDecoration(
                borderRadius: BorderRadius.all(Radius.circular(8.r)),
                color: const Color(0x0A000000), //设置背景色为黑色
              ),
              height: 36.w,
              child: Center(
                  child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Image(image: const AssetImage('assets/images/ic_home_search.png'), width: 24.w, height: 24.w),
                  const Text(
                    '搜索',
                    style: TextStyle(
                        fontFamily: "PingFang SC", fontWeight: FontWeight.w400, fontSize: 16, color: Color(0xFF8C8C8C)),
                  ),
                ],
              )),
            ),
          ),
          actions: [
            GestureDetector(
              onTap: () {
                EcyRouter.pushNoParams(context, EcyRouter.cardDetailPage);
              },
              child: Stack(alignment: Alignment.topRight, children: [
                Padding(
                  padding: const EdgeInsets.only(right: 10),
                  child: Image(image: const AssetImage('assets/images/ic_home_gwc.png'), width: 24.w, height: 30.w),
                ),
                if (cartNum > 0)
                  Positioned(
                    right: 2,
                    top: 0,
                    child: Container(
                      padding: EdgeInsets.all(cartNum > 9 ? 2 : 3),
                      decoration: const BoxDecoration(
                        color: Colors.red,
                        shape: BoxShape.circle, // 圆形角标（可选rectangle矩形）
                        // 矩形样式示例：
                        // borderRadius: BorderRadius.circular(10),
                      ),
                      child: Text(
                        '${cartNum > 99 ? '99+' : cartNum}',
                        style: TextStyle(
                            fontFamily: "PingFag SC", fontWeight: FontWeight.w400, fontSize: 8.sp, color: Colors.white),
                        textAlign: TextAlign.center,
                      ),
                    ),
                  )
              ]),
            ),
          ],
        ),
        body: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
          Container(
              color: const Color(0xFFFFFFFF),
              height: 35.w,
              child: SizedBox.fromSize(
                size: Size(MediaQuery.of(context).size.width, 35.w),
                child: labelListView,
              )),
          Expanded(
              child: PageView(
            controller: _pageController,
            allowImplicitScrolling: true,
            onPageChanged: (page) {
              labelListView.onCurrentIndexChange(page);
            },
            children: [
              goodsFirstPage,
              blindBoxPage,
              newGoodsView,
            ],
          )),
        ]));
  }

  @override
  void dispose() {
    // 清理控制器，避免内存泄漏
    super.dispose();
    _pageController.dispose();
  }
}
